//
//  YCAddressBookViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/11.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  通讯录

#import "YCAddressBookViewController.h"
#import "YCCustomersHeaderView.h"
//#import "contactChat.h"//获取联系人


NSString * const GOAddressBookKeysKey = @"keys";
NSString * const GOAddressBookItemsKey = @"items";

#pragma mark -
#pragma mark - YCAddressBookCell

@interface YCAddressBookCell : UITableViewCell

@property (readonly ,nonatomic) UIImageView *headerImageView;
@property (readonly ,nonatomic) UILabel *nameLabel;

@end

@implementation YCAddressBookCell

@synthesize headerImageView = _headerImageView;
@synthesize nameLabel = _nameLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        _headerImageView = [[UIImageView alloc] init];
        _headerImageView.contentMode = UIViewContentModeScaleAspectFill;
        _headerImageView.image = [UIImage yc_roundPlaceHolderImageForSize:CGSizeMake(37.0, 37.0)];
        _headerImageView.layer.cornerRadius = 37/2;
        _headerImageView.layer.masksToBounds = YES;
        [self.contentView addSubview:_headerImageView];
        
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.font = [UIFont systemFontOfSize:15];
        _nameLabel.textAlignment = NSTextAlignmentLeft;
        [self.contentView addSubview:_nameLabel];
        
        [_headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@15);
            make.centerY.equalTo(self.contentView);
            make.width.and.height.equalTo(@37);
        }];
        
        [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_headerImageView.mas_right).offset(10);
            make.right.equalTo(self.contentView).offset(-62);
            make.centerY.equalTo(self.contentView);
        }];
        
    }
    return self;
}


@end

#pragma mark -
#pragma mark - YCAddressBookViewController

@interface YCAddressBookViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UISearchBarDelegate,UISearchDisplayDelegate>

@property (readonly  ,nonatomic) UIView *headerView;
@property (readonly  ,nonatomic) UIButton *searchButton;
@property (readonly  ,nonatomic) UISegmentedControl *segmentedControl;
@property (readonly  ,nonatomic) UITableView *tableView;
@property (nonatomic ,copy)      NSArray *businessIndexs;
@property (nonatomic ,strong)    NSMutableDictionary *businessDataDictionary;
@property (nonatomic ,copy)      NSArray *friendsIndexs;
@property (nonatomic ,strong)    NSMutableDictionary *friendsDataDictionary;
@property (nonatomic ,readonly)  UISearchBar *searchBar;
@property (nonatomic ,readonly)  UISearchDisplayController *displayController; //
@property (nonatomic ,copy)      NSArray *searchArray;
@property (nonatomic ,readonly)  NSMutableArray *alldatas;
@property (nonatomic,readonly)   JSBadgeView *badgeView;

@end

@implementation YCAddressBookViewController

@synthesize headerView = _headerView;
@synthesize searchButton = _searchButton;
@synthesize segmentedControl = _segmentedControl;
@synthesize tableView = _tableView;
@synthesize searchBar = _searchBar;
@synthesize displayController = _displayController;
@synthesize alldatas = _alldatas;

#pragma mark - 属性获取方法

- (UIView *)headerView
{
    if (!_headerView)
    {
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    
    return _headerView;
}

// 搜索按钮
- (UIButton *)searchButton
{
    if (!_searchButton)
    {
        _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchButton setTitle:@"搜索" forState:UIControlStateNormal];
        [_searchButton setTitleColor:[UIColor yc_colorWithUInt:0x8c8c8c] forState:UIControlStateNormal];
        _searchButton.backgroundColor = [UIColor yc_colorWithUInt:0xeaebed];
        _searchButton.layer.cornerRadius = 5;
        _searchButton.layer.masksToBounds = YES;
        _searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [_searchButton setImage:[UIImage imageNamed:@"business_search"] forState:UIControlStateNormal];
        _searchButton.imageView.contentMode = UIViewContentModeCenter;
        [_searchButton addTarget:self action:@selector(didTouchUpInsideSearchButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _searchButton;
}

- (NSMutableArray *)alldatas
{
    if (!_alldatas)
    {
        _alldatas = [[NSMutableArray alloc] init];
    }
    
    return _alldatas;
}

// 搜索条
- (UISearchBar *)searchBar
{
    if(!_searchBar)
    {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.yc_width, 48.0)];
        _searchBar.delegate = self;
        _searchBar.backgroundImage = [UIImage yc_imageWithColor:[UIColor yc_colorWithUInt:0xf1f0f6] size:CGSizeMake(self.view.yc_width, 48.0)];
        _searchBar.tintColor = [UIColor blackColor];
        
        // 搜索结果显示控制器
        _displayController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
        _displayController.searchResultsDataSource = self;
        _displayController.searchResultsDelegate = self;
        _displayController.delegate = self;
        
        _displayController.searchResultsTableView.rowHeight = 55.0;
        _displayController.searchResultsTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        _displayController.searchResultsTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.1)];
        _displayController.searchResultsTableView.backgroundColor = [UIColor yc_colorWithUInt:0xf1f0f6];
    }
    return _searchBar;
}


- (UISegmentedControl *)segmentedControl
{
    if (!_segmentedControl)
    {
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"所有学员(598)",@"好友(124)"]];
        _segmentedControl.translatesAutoresizingMaskIntoConstraints = NO;
        _segmentedControl.tintColor = [UIColor blackColor];
        _segmentedControl.selectedSegmentIndex = 1;
        [_segmentedControl addTarget:self action:@selector(didChangeValueOfSegmentedControl:) forControlEvents:UIControlEventValueChanged];
        _segmentedControl.hidden = NO;
    }
    
    return _segmentedControl;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 55.0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.sectionIndexColor = [UIColor grayColor];
//        _tableView.backgroundColor = [UIColor greenColor];
        // 索引条
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
        
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.1)];
    }
    
    return _tableView;
}

#pragma mark - 视图控制器生命周期

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    [self.displayController.searchResultsTableView go_clearSeparatorInset];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"gonewfriend" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"通讯录", nil);
    [self yc_addBackBarButtonItem];
    [self yc_addRightDoneBarButtonItemWithTitle:@"新朋友" target:self action:@selector(didTouchUpInsideNewFriendsBarButtonItem:)];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 28)];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:self action:@selector(didTouchUpInsideNewFriendsBarButtonItem:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor yc_colorWithUInt:0x00b4ff] forState:UIControlStateNormal];
    [button setTitle:@"新朋友" forState:UIControlStateNormal];
    
    UIBarButtonItem *addressBookitem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = addressBookitem;
    
    _badgeView = [[JSBadgeView alloc] initWithParentView:addressBookitem.customView alignment:JSBadgeViewAlignmentTopRight];
    
//    @go_weakify(self);
//    
//    [self.KVOController observe:[GONewFriendManger manager] keyPath:@"newFriendRequestCount"
//                        options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial
//                          block:^(id observer, id object, NSDictionary *change) {
//                              
//                              @go_strongify(self);
//                              if(!self) return ;
//                              
//                              NSInteger count = [change[NSKeyValueChangeNewKey] integerValue];
//                              if(count > 0)
//                              {
//                                  self.badgeView.badgeText = [NSString stringWithFormat:@"%ld",count];
//                              }
//                              else
//                              {
//                                  self.badgeView.badgeText = nil;
//                              }
//                          }];
    
    [self layout];
    
//    [self friendsRequest];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"gonewfriend" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNewFriendNotification:) name:@"gonewfriend" object:nil];
}

#pragma mark - 自定义的方法

- (void)layout
{
    [self.headerView addSubview:self.searchButton];
    [self.headerView addSubview:self.segmentedControl];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.headerView];
    
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView).offset(10);
        make.left.equalTo(self.headerView).offset(30);
        make.right.equalTo(self.headerView).offset(- 30);
        make.height.equalTo(@25);
    }];
    
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchButton.mas_bottom).offset(15);
        make.centerX.equalTo(self.headerView);
//        make.width.equalTo(@(kScreenWidth / 3));
        make.left.equalTo(self.headerView).offset(50);
        make.right.equalTo(self.headerView).offset(-50);
        make.height.equalTo(@25);
    }];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.segmentedControl.mas_bottom).offset(15);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
}

- (void)didReceiveNewFriendNotification:(NSNotification *)notification
{
//    [self friendsRequest];
}

///新朋友
- (void)didTouchUpInsideNewFriendsBarButtonItem:(UIButton *)button
{
//    GONewFriendsViewController *vc = [[GONewFriendsViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}

///搜索
- (void)didTouchUpInsideSearchButton:(UIButton *)button
{
    if(!self.searchBar.window)
    {
        [self.navigationController.view addSubview:self.searchBar];
    }
    [self.displayController setActive:YES animated:YES];
    [self.searchBar becomeFirstResponder];
}

///
- (void)didChangeValueOfSegmentedControl:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0)
    {
        if (self.businessIndexs.count == 0)
        {
//            [self coustomerListRequest];
            return ;
        }
        
        [self.tableView reloadData];
    }
    else
    {
        if (self.friendsIndexs.count == 0)
        {
//            [self friendsRequest];
            return ;
        }
        
        [self.tableView reloadData];
    }
}

#pragma mark - UITableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView)
    {
        //        if (_segmentedControl.selectedSegmentIndex == 0)
        //        {
        //            return self.businessIndexs.count;
        //        }
        //        else
        {
            return self.friendsIndexs.count;
        }
    }
    else
    {
        return 1;
    }
    
}

//返回索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == self.tableView)
    {
        //        if (_segmentedControl.selectedSegmentIndex == 0)
        //        {
        //            return self.businessIndexs;
        //        }
        
        return self.friendsIndexs;
    }
    else
    {
        return nil;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView)
    {
        //        if (_segmentedControl.selectedSegmentIndex == 0)
        //        {
        //            return [self.businessDataDictionary[self.businessIndexs[section]] count];
        //        }
        
        return [self.friendsDataDictionary[self.friendsIndexs[section]] count];
    }
    else
    {
        return self.searchArray.count;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView)
    {
        static NSString *HEAD = @"HEAD";
        YCCustomersHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HEAD];
        if(!headerView)
        {
            headerView = [[YCCustomersHeaderView alloc] initWithReuseIdentifier:HEAD];
        }
        //        if (_segmentedControl.selectedSegmentIndex == 0)
        //        {
        //            headerView.titleLabel.text = self.businessIndexs[section];
        //        }
        //        else
        {
            headerView.titleLabel.text = self.friendsIndexs[section];
        }
        
        return headerView;
    }
    else
    {
        return nil;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    NSInteger count = 0;
    
    if (self.tableView == tableView)
    {
        count = 30;
    }
    else
    {
        count = 0;
    }
    
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *iden = @"IDEN";
    YCAddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (!cell)
    {
        cell = [[YCAddressBookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
    }
    if (self.tableView == tableView)
    {
        //        if (_segmentedControl.selectedSegmentIndex == 0)
        //        {
        //            NSMutableArray *array = self.businessDataDictionary[self.businessIndexs[indexPath.section]];
        //            GOBusiness *model = array[indexPath.row];
        //            [cell.headerImageView go_setWebImageWithURLString:model.businessLogo holderSize:CGSizeMake(37, 37)];
        //            cell.nameLabel.text = model.businessSuppliersName;
        //
        //        }
        //        else
        {
            NSMutableArray *array = self.friendsDataDictionary[self.friendsIndexs[indexPath.section]];
//            GOCustomerUser *model = array[indexPath.row];
//            [cell.headerImageView go_setWebImageWithURLString:model.cuHeadPhoto holderSize:CGSizeMake(37, 37)];
//            cell.nameLabel.text = model.cuNickName;
            
        }
        
    }
    else
    {
        NSDictionary *rowData = self.searchArray[indexPath.row];
        // 头像
        [cell.headerImageView yc_setWebImageWithURLString:rowData[@"logo"] holderSize:CGSizeMake(37, 37)];
        cell.nameLabel.text = rowData[@"nickName"];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [cell go_clearSeparatorInset];
}

// 支持左滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (_segmentedControl.selectedSegmentIndex == 0)
//    {
//        NSMutableArray *array = self.businessDataDictionary[self.businessIndexs[indexPath.section]];
//        GOBusiness *business = array[indexPath.row];
//
//        UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"解除联盟" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//
//            NSMutableDictionary *ps = [[NSMutableDictionary alloc] init];
//
//            if (!business.businessTargetSuppliersId)
//            {
//                [SVProgressHUD showErrorWithStatus:@"未获取到联盟Id..."];
//                return ;
//            }
//            else
//            {
//                ps[@"targetSuppliersId"] = business.businessTargetSuppliersId;
//            }
//
//            if (![GOLoginUser loginUser].userSupplierId)
//            {
//                [SVProgressHUD showErrorWithStatus:@"未绑定商家Id..."];
//                return ;
//            }
//            else
//            {
//                ps[@"suppliersId"] = [GOLoginUser loginUser].userSupplierId;
//            }
//
//            @go_weakify(self);
//
//            GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                if(response.success)
//                {
//                    @go_strongify(self);
//                    if (!self) return ;
//
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//                        [SVProgressHUD dismiss];
//
//                        [array removeAllObjects];
//
//                        self.businessDataDictionary[self.businessIndexs[indexPath.section]] = array;
//
//                        [self coustomerListRequest];
//
//                    });
//                }
//            };
//
//            GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//
//            };
//
//            [SVProgressHUD showWithStatus:@"正在解除..."];
//
//            [[GOWebService service] postAction:GOAPISuppliersAllianceUnAlliance
//                                        params:ps
//                                       success:success
//                                       failure:failure];
//
//        }];
//
//        return @[deleteAction];
//    }
//
//    return nil;
//}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    if (_segmentedControl.selectedSegmentIndex == 1)
    {
        NSMutableArray *array = self.friendsDataDictionary[self.friendsIndexs[indexPath.section]];
//        GOCustomerUser *user = array[indexPath.row];
//        
//        if (!user.cuUserFriendRelationId)
//        {
//            [SVProgressHUD showErrorWithStatus:@"未获取到好友Id..."];
//            return;
//        }
//        
//        @go_weakify(self);
//        
//        GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//            if(response.success)
//            {
//                @go_strongify(self);
//                if (!self) return ;
//                
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    
//                    [SVProgressHUD dismiss];
//                    
//                    [array removeAllObjects];
//                    
//                    self.friendsDataDictionary[self.friendsIndexs[indexPath.section]] = array;
//                    
//                    [self friendsRequest];
//                });
//            }
//        };
//        
//        GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        };
//        
//        [SVProgressHUD showWithStatus:@"正在删除好友..."];
//        
//        [[GOWebService service] postAction:GOAPIUserFriendsDelete
//                                    params:@{@"relationId":user.cuUserFriendRelationId}
//                                   success:success
//                                   failure:failure];
//        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    if (_segmentedControl.selectedSegmentIndex == 0)
    //    {
    ////        NSMutableArray *array = self.businessDataDictionary[self.businessIndexs[indexPath.section]];
    ////        GOBusiness *business = array[indexPath.row];
    //    }
    //    else
    /*
    {
        NSMutableArray *array = self.friendsDataDictionary[self.friendsIndexs[indexPath.section]];
        GOCustomerUser *customer = array[indexPath.row];
        contactChat *chat = [contactChat createOrUpdateContactChat:customer];
        
        GVIndexViewController *vc = [[GVIndexViewController alloc] initWithContactChat:chat];
        //[self.navigationController popViewControllerAnimated:YES];
        [self.navigationController pushViewController:vc animated:YES];
    }*/
}

#pragma mark -- UISearchBar delegate

#pragma mark -- UISearchDisplay delegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    for (UIView *subview in self.displayController.searchResultsTableView.subviews)
    {
        if ([subview isKindOfClass:[UILabel class]])
        {
            UILabel *label = (UILabel *)subview;
            label.text = @"";
            break;
        }
    }
    NSString *key = searchString.uppercaseString;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.nickName CONTAINS[d] %@ OR SELF.pinyin CONTAINS[d] %@ OR SELF.letter CONTAINS[d] %@ OR SELF.key CONTAINS[d]%@",key,key,key,key];
    self.searchArray = [self.alldatas filteredArrayUsingPredicate:predicate];
    
    return YES;
}


#pragma mark - 数据请求
/*
- (void)friendsRequest
{
    [self.tableView.go_loadingView startAnimating];
    
    [[GOWebService service]postAction:GOAPIUserFriendsGetAllFriends
                               params:@{}
                              success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
                                  
                                  dispatch_async(dispatch_get_main_queue(), ^{
                                      [self.tableView.go_loadingView stopAnimating];
                                  });
                                  
                                  @go_weakify(self);
                                  
                                  if (response.success)
                                  {
                                      NSArray *array = response.data;
                                      
                                      NSError *error;
                                      
                                      NSArray *objects = [MTLJSONAdapter modelsOfClass:[GOCustomerUser class] fromJSONArray:array error:&error];
                                      NSMutableDictionary *datas = [[NSMutableDictionary alloc] init];
                                      NSMutableArray *indexs = [[NSMutableArray alloc] init];
                                      
                                      if(!error)
                                      {
                                          NSMutableArray *userArray = [[NSMutableArray alloc] init];
                                          [userArray addObjectsFromArray:objects];
                                          
                                          for (GOCustomerUser *c in userArray)
                                          {
                                              NSDictionary *info = [c.cuNickName go_PINYINInfo];
                                              c.cuFirstLetter = info[@"letter"];
                                              c.cuPinyin = info[@"pinyin"];
                                              c.cuKey = info[@"key"];
                                              
                                              NSString *key = c.cuFirstLetter ? c.cuFirstLetter : @"#";
                                              
                                              if (![key isEqualToString:c.cuFirstLetter])
                                              {
                                                  key = c.cuFirstLetter;
                                              }
                                              
                                              NSMutableArray *array = datas[key];
                                              if(!array)
                                              {
                                                  array = [[NSMutableArray alloc] init];
                                                  datas[key] = array;
                                                  [indexs addObject:key];
                                              }
                                              [array addObject:c];
                                              
                                              NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                                              dict[@"userID"] = c.cuUserId;
                                              dict[@"nickName"] = c.cuNickName;
                                              dict[@"letter"] = c.cuFirstLetter;
                                              dict[@"pinyin"] = c.cuPinyin;
                                              dict[@"key"] = c.cuKey;
                                              dict[@"logo"] = c.cuHeadPhoto;
                                              
                                              [self.alldatas addObject:dict];
                                          }
                                          
                                          @go_strongify(self);
                                          if(!self) return;
                                          
                                          self.friendsIndexs = [indexs sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                                              return [obj1 compare:obj2];
                                          }];
                                          self.friendsDataDictionary = datas;
                                          
                                          [self.tableView reloadData];
                                      }
                                      
                                  }
                                  
                              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                  
                              }];
}

- (void)coustomerListRequest
{
    [self.tableView.go_loadingView startAnimating];
    
    NSMutableDictionary *ps = [@{@"pageSize":@(1000),
                                 @"pageNo":@(1)} mutableCopy];
    
    if (![GOLoginUser loginUser].userSupplierId)
    {
        [SVProgressHUD showErrorWithStatus:@"未绑定商家Id..."];
        return;
    }
    else
    {
        ps[@"suppliersId"] = [GOLoginUser loginUser].userSupplierId;
    }
    
    @go_weakify(self);
    
    GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.go_loadingView stopAnimating];
            [self.tableView.infiniteScrollingView stopAnimating];
        });
        
        if(response.success)
        {
            NSArray *listData = [response.data isKindOfClass:[NSDictionary class]] ? response.data[@"listData"] : @[];
            
            NSError *error;
            
            NSArray *objects = [MTLJSONAdapter modelsOfClass:[GOBusiness class] fromJSONArray:listData error:&error];
            
            NSMutableDictionary *datas = [[NSMutableDictionary alloc] init];
            NSMutableArray *indexs = [[NSMutableArray alloc] init];
            
            if(!error)
            {
                NSMutableArray *bsuinessArray = [[NSMutableArray alloc] init];
                [bsuinessArray addObjectsFromArray:objects];
                
                for (GOBusiness *c in bsuinessArray)
                {
                    NSDictionary *info = [c.businessSuppliersName go_PINYINInfo];
                    c.businessFirstLetter = info[@"letter"];
                    c.businessPinyin = info[@"pinyin"];
                    c.businessKey = info[@"key"];
                    
                    NSString *key = c.businessFirstLetter ? c.businessFirstLetter : @"#";
                    
                    if (![key isEqualToString:c.businessFirstLetter])
                    {
                        key = c.businessFirstLetter;
                    }
                    
                    NSMutableArray *array = datas[key];
                    if(!array)
                    {
                        array = [[NSMutableArray alloc] init];
                        datas[key] = array;
                        [indexs addObject:key];
                    }
                    [array addObject:c];
                    
                    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                    dict[@"userID"] = c.businessUserId;
                    dict[@"nickName"] = c.businessSuppliersName;
                    dict[@"letter"] = c.businessFirstLetter;
                    dict[@"pinyin"] = c.businessPinyin;
                    dict[@"key"] = c.businessKey;
                    dict[@"logo"] = c.businessLogo;
                    
                    [self.alldatas addObject:dict];
                }
                
                @go_strongify(self);
                if(!self) return;
                
                self.businessIndexs = [indexs sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                    return [obj1 compare:obj2];
                }];
                self.businessDataDictionary = datas;
                
                [self.tableView reloadData];
            }
        }
        else
        {
            
        }
    };
    
    GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
        
    };
    
    [[GOWebService service] postAction:GOAPISuppliersAllianceGetListBySuppliersId
                                params:ps
                               success:success
                               failure:failure];
}
*/

@end
